﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using mBlogAPI;
using mBlogAPI.Utils;
using mBlogAPI.BL;
using System.IO.IsolatedStorage;
using System.IO;
using mBlogAPI.Schema;
using System.Collections.ObjectModel;

namespace MyDesktopMicroBlog
{
    /// <summary>
    /// Interaction logic for LoginWindow.xaml
    /// </summary>
    public partial class LoginWindow : Window
    {
        List<UserSettings> TokenList = Configurations.GetTokenList();
        public LoginWindow()
        {
            InitializeComponent();
            InitAuthorizeInformation();
            cmbUserList.ItemsSource = TokenList;
        }

        public void InitAuthorizeInformation()
        {
            WebRequestHelper.SetOAuthBaseUrl(
             Application.Current.Resources["RequestTokenUrl"].ToString(),
             Application.Current.Resources["AuthorizationTokenUrl"].ToString(),
             Application.Current.Resources["AccessTokenUrl"].ToString(),
             Application.Current.Resources["ConsumerKey"].ToString(),
             Application.Current.Resources["ConsumerSecret"].ToString(),
             Application.Current.Resources["APIBaseUrl"].ToString());
            try
            {
                browserLogin.Navigate(WebRequestHelper.GetAuthorizationUrl());
            }
            catch (Exception ex)
            {
                LogHelper.LogError(ex);
                MessageBox.Show("网络连接失败，请检查网络");
            }
        }

        private void browserLoginControl_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            if (e.Uri.Host == "api.t.sohu.com")
            {
                if (e.Uri.AbsolutePath == "/unauthorize.jsp")
                {
                    Application.Current.Shutdown();
                }
                else if (e.Uri.AbsolutePath == "/oauth/oob")
                {
                    try
                    {
                        WebRequestHelper.GenerateAccessToken(QueryStringUtils.ParseQuery(e.Uri.ToString())["oauth_verifier"]);
                        UserBL.CacheCurrentUser();
                        if (chkRememberme.IsChecked.Value)
                        {
                            Configurations.SaveToken(WebRequestHelper.AccessToken, WebRequestHelper.AccessTokenSecret, UserBL.CurrentUser);
                        }
                        OpenMainWindow();
                    }
                    catch (Exception ex)
                    {
                        LogHelper.LogError(ex);
                        MessageBox.Show("抱歉，登录失败了，请重试...");
                    }
                }
            }
        }

        private void OpenMainWindow()
        {
            MainWindow mainWindow = new MainWindow();
            mainWindow.WindowState = System.Windows.WindowState.Normal;
            Application.Current.MainWindow = mainWindow;
            mainWindow.Show();
            mainWindow.Activate();
            this.Close();
        }

        private void btnLogin_Click(object sender, RoutedEventArgs e)
        {
            string userID = cmbUserList.SelectedValue.ToString();
            if (!string.IsNullOrEmpty(userID) && userID != "-1")
            {
                UserSettings token = Configurations.GetToken(cmbUserList.SelectedValue.ToString());
                WebRequestHelper.SetAccessToken(token);
                try
                {
                    UserBL.CacheCurrentUser();
                    OpenMainWindow();
                }
                catch (Exception ex)
                {
                    LogHelper.LogError(ex);
                    MessageBox.Show("抱歉，登录失败了，请重试...");
                }
            }
            else
            {
                cmbUserList.SelectedValue = "-1";
            }
        }

        private void btnDeleteMe_Click(object sender, RoutedEventArgs e)
        {
            string deleteKey = (sender as Button).CommandParameter.ToString();
            TokenList = Configurations.DeleteToke(deleteKey);
            cmbUserList.ItemsSource = TokenList;
        }

        private void btnClose_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private double _height;
        private double _width;
        private void cmbUserList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cmbUserList.SelectedValue != null && cmbUserList.SelectedValue.ToString() == "-1")
            {
                this._height = this.Height;
                this._width = this.Width;
                this.Height = 490;
                this.Width = 550;
                browserLogin.Visibility = System.Windows.Visibility.Visible;
            }
            else
            {
                this.Height = _height;
                this.Width = _width;
                browserLogin.Visibility = System.Windows.Visibility.Collapsed;
            }
        }

        private void browserLogin_LoadCompleted(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            if (browserLogin.Source.AbsolutePath == "/oauth/authorize")
            {
                    mshtml.HTMLDocument document = browserLogin.Document as mshtml.HTMLDocument;
                    document.parentWindow.scrollTo(0, 100);
                    document.body.setAttribute("scroll", "no");
            }
        }
    }
}
